//
//  NewAddressViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/16.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "NewAddressViewController.h"

@interface NewAddressViewController ()<UIPickerViewDataSource, UIPickerViewDelegate>
{
    NSString * address;
    NSString * chooseCidStr;
    NSString * areaIdStr;  // 城市选择id
    
    // 地区选择
    NSInteger _provinceIndex;   // 省份选择 记录
    NSInteger _cityIndex;       // 市选择 记录
    NSUInteger _areaIndex;      // 地区 记录
    
    NSString * provinceIdStr;  //省级代码
    NSString * cityIdStr;     //市级代码


}
@property (weak, nonatomic) IBOutlet UITextField *nameLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *areText;

@property (weak, nonatomic) IBOutlet UITextField *addressText;
@property (weak, nonatomic) IBOutlet UIButton *keepBtn;

@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong) NSArray * arrayDS;

@end

@implementation NewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TitleView(@"添加收货地址")
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    
    self.arrayDS = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableLeaves error:nil];

    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(back)];
    
    self.keepBtn.layer.cornerRadius = 45/2.f;
    self.keepBtn.layer.masksToBounds = YES;
    
     _areText.inputView = self.pickerView;
    
}


-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)keepBtnClick:(id)sender {
    
    if (_nameLabel.text.length<=0||_nameLabel.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入收货人");
        return;
    }
    if (_phoneText.text.length<=0||_phoneText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入联系电话");
        return;
    }
    if (_areText.text.length<=0||_areText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请选择城市");
        return;
    }
    if (_addressText.text.length<=0||_addressText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入详细地址");
        return;
    }

    //添加收货地址
    [self requestAddressForNet];
}


-(void)initData
{
    _provinceIndex = _cityIndex =  0;
}


// 懒加载方式
-(UIPickerView *)pickerView

{
    if(!_pickerView){
        
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT - 216, WIDTH, 216)];
        _pickerView.dataSource = self;
        _pickerView.backgroundColor =[UIColor groupTableViewBackgroundColor];
        _pickerView.delegate = self;
        _pickerView.userInteractionEnabled =YES;
        
    }
    return _pickerView;
}

-(void)resetPickerSelectRow
{
    [self.pickerView selectRow:_provinceIndex inComponent:0 animated:YES];
    [self.pickerView selectRow:_cityIndex inComponent:1 animated:YES];
    [self.pickerView selectRow:_areaIndex inComponent:2 animated:YES];
    
}

#pragma mark - PickerView Delegate

// 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

// 每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if(component == 0){
        
        
        return self.arrayDS.count;
    }
    else if (component == 1){
        return [self.arrayDS[_provinceIndex][@"sub"] count];
    }else {
        
        return [self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"] count];
    }
    
}

// 返回每一行的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0){
        return self.arrayDS[row][@"area"];
    }
    else if (component == 1){
        return self.arrayDS[_provinceIndex][@"sub"][row][@"area"];
    }
    else{
        return self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][row][@"area"];
    }
}

// 滑动或点击选择，确认pickerView选中结果
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if(component == 0){
        _provinceIndex = row;
        _cityIndex = 0;
        _areaIndex = 0;
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
        
    }
    else if (component == 1){
        _cityIndex = row;
        _areaIndex = 0;
        
        [self.pickerView reloadComponent:2];
        
        
    }
    else{
        
        _areaIndex = row;
        
    }
    // 重置当前选中项
    [self resetPickerSelectRow];
    address = [NSString stringWithFormat:@"%@ %@ %@", self.arrayDS[_provinceIndex][@"area"], self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"area"],self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][_areaIndex][@"area"]];
    
    provinceIdStr = self.arrayDS[_provinceIndex][@"area_id"];
    cityIdStr = self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"area_id"];
    areaIdStr = self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][_areaIndex][@"area_id"];
    
    _areText.text = address;
    
}


//新增地址

-(void)requestAddressForNet{
    
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"name":self.nameLabel.text,
                           @"phone":self.phoneText.text,
                           @"area":self.areText.text,
                           @"addr":self.addressText.text
                           };
    SHuiMBhubNoTimeStr(@"正在添加...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(add_address_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            SHuiMBhudTextTimeStr(@"添加成功！");
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
        
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
